<template>

  <a-layout>
    <a-layout-content
        :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
    >
      <p>
        <a-space size="large">
          <a-input v-model:value="queryValue" placeholder="Input ebook name" size="large"/>
          <a-button type="primary" size="large"
                    @click="handleQuery({page: 1, size: pagination.pageSize, name: queryValue})">
            <template #icon>
              <SearchOutlined/>
            </template>
            Search
          </a-button>
          <a-button size="large" @click="handleQuery({page: 1, size: pagination.pageSize})">
            Cancel Search
          </a-button>
          <a-button type="primary" @click="add" size="large">
            Create
          </a-button>
        </a-space>
      </p>
      <a-table
          :columns="columns"
          :row-key="record => record.id"
          :data-source="ebooks"
          :pagination="pagination"
          :loading="loading"
          @change="handleTableChange"
      >
        <!--点击分页时会执行handleTableChange方法-->
        <template #cover="{ text: cover }">
          <img v-if="cover" :src="cover" alt="avatar"/>
        </template>
        <template v-slot:category="{text, record}">
          <span>{{ getCategoryName(record.category1Id) }} / {{ getCategoryName(record.category2Id) }}</span>
        </template>
        <template v-slot:action="{text, record}"> <!--record是按钮所对应的行的数据-->
          <a-space size="small"> <!-- <a-space> : 空格组件，两个按钮要用空格隔开-->
            <router-link :to="'/admin/doc?ebookId='+ record.id">
            <a-button type="primary">
              Doc
            </a-button>
            </router-link>
            <a-button type="primary" @click="edit(record)">
              Edit
            </a-button>
            <a-popconfirm
                title="Are you sure delete this ebook?"
                ok-text="Yes"
                cancel-text="No"
                @confirm="confirm(record.id)"
            >
              <a-button type="danger">
                Delete
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-layout-content>
  </a-layout>
  <a-modal
      v-model:visible="modalVisible"
      title="电子书表单"
      :confirm-loading="modalConfirmLoading"
      @ok="modalHandleOk"
  >
    <a-form :model="ebook" :label-col="{span : 6}" :wrapper-col="{ span: 18 }">
      <a-form-item label="封面">
        <a-input v-model:value="ebook.cover"/>
      </a-form-item>
      <a-form-item label="名称">
        <a-input v-model:value="ebook.name"/>
      </a-form-item>
      <a-form-item label="分类">
        <a-cascader
            v-model:value="categoryIds"
            :options="level1"
            :field-names="{label: 'name', value: 'id', children: 'children'}"
            placeholder="Please select"
        />
        <!--        label:显示的字段，value：实际值-->
      </a-form-item>
      <a-form-item label="描述">
        <a-input v-model:value="ebook.description"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts">
import {defineComponent, onMounted, ref} from "vue";
import {message} from 'ant-design-vue';
import axios from "axios";
import {SearchOutlined} from '@ant-design/icons-vue';
import {Tool} from "@/util/tool"

export default defineComponent({
  components: {
    SearchOutlined,
  },
  name: 'AdminEbook',
  setup() {
    const queryValue = ref<string>(''); // 搜索框内容
    const ebooks = ref();
    /*
    数组：[100,101] 对应：前端开发/Vue
    */
    const level1 = ref();
    const categoryIds = ref();
    const ebook = ref();
    const pagination = ref({
      current: 1,
      pageSize: 5,
      total: 0
    });
    const loading = ref(false);
    const columns = [
      {
        title: '封面',
        dataIndex: 'cover',
        slots: {customRender: 'cover'}
      },
      {
        title: '名称',
        dataIndex: 'name'
      },
      {
        title: '分类',
        slots: {customRender: 'category'}
      },
      {
        title: '文档数',
        dataIndex: 'docCount'
      },
      {
        title: '阅读数',
        dataIndex: 'viewCount'
      },
      {
        title: '点赞数',
        dataIndex: 'voteCount'
      },
      {
        title: 'Action',
        key: 'action',
        slots: {customRender: 'action'}
      }
    ];
    // const modalText = ref<string>('Content of the modal');

    /*
    * 查询相关函数
    *
    */
    const ebookQuery = (queryValue: string) => {
      axios.get("/ebook/list", {
        params: {
          name: queryValue
        }
      }).then((response) => {
        const data = response.data;
        if (data.success) {
          ebooks.value = data.content.list; // ebooks的数据在content下面的list中

          // 重置分页按钮
          pagination.value.current = 1;
          pagination.value.total = data.content.total;
        }
      })
    }

    /**
     * 删除相关函数
     */
    const confirm = (id: number) => {
      // console.log(e);
      // ebook.value = record;
      axios.delete("/ebook/delete/" + id).then((response) => {
        const data = response.data;
        if (data.success) { // data 等于 CommonResp
          message.success('Deleted Successfully');
          // 重新加载列表
          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize
          });
        }
      })
    };


    // const cancel = (e : MouseEvent) => {
    //    console.log(e);
    //   message.error('You canceled this deletion');
    // };

    /**
     * 增加相关函数
     */
    const add = (record: any) => {
      modalVisible.value = true;
      ebook.value = {};
    };
    /**
     * 编辑按钮相关
     */
    const modalVisible = ref(false);
    const modalConfirmLoading = ref(false);

    const edit = (record: any) => {
      modalVisible.value = true;
      ebook.value = Tool.copy(record);
      categoryIds.value = [ebook.value.category1Id, ebook.value.category2Id];
    };

    const modalHandleOk = () => {
      // modalText.value = 'The modal will be closed after two seconds';
      modalConfirmLoading.value = true;
      ebook.value.category1Id = categoryIds.value[0];
      ebook.value.category2Id = categoryIds.value[1];
      axios.post("/ebook/save", ebook.value).then((response) => {
        modalConfirmLoading.value = false;
        const data = response.data;
        if (data.success) { // data 等于 CommonResp
          modalVisible.value = false;
          // 重新加载列表
          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize
          });
        } else {
          message.error(data.message);
        }
      })
    };

    /*
      查询所有分类
    */
    let categorys: any;
    const handleQueryCategory = () => {
      loading.value = true;
      axios.get("/category/all").then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          categorys = data.content; // categorys的数据在content
          console.log("原始数组：", categorys);
          level1.value = [];
          level1.value = Tool.array2Tree(categorys, 0);
          console.log("树形结构：", level1);
          // 加载完分类后，再加载电子书，否则如果分类树加载很慢，则电子书渲染会报错
          handleQuery({ // 通过下面的数据传给方法里面的params，params通过axios传给后端
            page: 1, // 加载第一页，这里的page要和后端接收的类中的属性名保持一致。
            size: pagination.value.pageSize // 用pagination的原因：ui分页组件里面对应的参数就叫pagination,里面的属性也是pageSize。其他同上，保持一致。
          });
        } else {
          message.error(data.message);
        }
      })
    }
    /**
     * 根据分类id查找分类名
     */
    const getCategoryName = (cid: number) => {
      let result = "";
      categorys.forEach((item: any) => {
        if (item.id == cid) {
          result = item.name;
        }
      });
      return result;
    }
    /**
     * 数据查询
     */
    const handleQuery = (params: any) => { // params:传递给后端的值。
      loading.value = true;
      // 如果不清空现有数据，则编辑保存重新加载数据后，再点编辑，则列表显示的还是编辑前的数据
      ebooks.value = [];
      axios.get("/ebook/list", {
        params: {
          page: params.page,
          size: params.size,
          name: params.name,
        }
      }).then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          ebooks.value = data.content.list; // ebooks的数据在content下面的list中

          // 重置分页按钮
          pagination.value.current = params.page;
          pagination.value.total = data.content.total;
        } else {
          message.error(data.message);
        }
      })
    }

    /**
     * 表格点击页码时触发
     */
    const handleTableChange = (pagination: any) => {
      console.log("看看自带的分页参数都有什么：" + pagination);
      handleQuery({
        page: pagination.current,
        size: pagination.pageSize
      });
    }

    // 初始的时候会先执行onMounted方法
    onMounted(() => {
      handleQueryCategory();
    });
    return {
      ebooks,
      pagination,
      columns,
      loading,
      handleTableChange,

      modalVisible,
      modalConfirmLoading,
      modalHandleOk,
      edit,

      ebook,

      add,

      confirm,
      // cancel,
      queryValue,
      ebookQuery,
      handleQuery,
      level1,
      categoryIds,
      getCategoryName,
    }
  }
})

</script>

<style>
img {
  width: 50px;
  height: 50px;
}
</style>

